package com.exp.sys.service.department;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import tk.mybatis.mapper.entity.Example;

import com.exp.sys.entity.Department;
import com.exp.sys.mapper.DepartmentMapper;
import com.exp.sys.service.BaseService;

public class DepartmentBaseService extends BaseService<Department,DepartmentMapper>{
	
	public DepartmentBaseService() {
		setEntityClass(Department.class);
	}
	
	@Resource
	@Override
	public void setMapper(DepartmentMapper mapper) {
		super.setMapper(mapper);
	}
	/**
	 * 更新时附带parentids的修改
	 * @param department
	 * @param sourcesDepartmentParentIds
	 */
	@Override
	public int update(Department department) {
		calculateFullId(department);
		return super.update(department);
	}
	
	@Override
	public int save(Department department) {
		String uuid = UUID.randomUUID().toString().replace("-", "");
		department.setId(uuid);
		calculateFullId(department);
		return super.save(department);
	}
	
	
	public void delete(String id,boolean deleteChild){
		Department department = get(id);
		Assert.notNull(department,"找不到部门"+id);
		if(deleteChild){
			Example example = new Example(Department.class);
			example.createCriteria().andLike("fullId", department.getFullId()+"%");
			this.delete(example);
		}else{
			delete(id);
			String parentFullId = department.getParentIds();
			Example example = new Example(Department.class);
			example.createCriteria().andEqualTo("parentId",id);
			List<Department> childDepartmentList = query(example);
			for(Department childDepartment : childDepartmentList){
				childDepartment.setParentId(department.getParentId());
				super.update(childDepartment);
			}
			updateFullId(department.getFullId(), parentFullId);
		}
	}
	
	/**
	 * 计算自己的fullId
	 * @param department
	 */
	public void calculateFullId(Department department){
		String parentId = department.getParentId();
		String fullId=null;
		if(StringUtils.isBlank(parentId)){
			fullId=department.getId();
		}else{
			Department departmentParent = get(parentId);
			Assert.notNull(departmentParent,"找不到父部门"+parentId);
			String parentFullId = departmentParent.getFullId();
			fullId = parentFullId+"."+department.getId();
		}
		department.setFullId(fullId);
	}
	/**
	 * 调整子节点的fullId
	 * @param departmentId
	 * @param sourcesDepartmentParentIds
	 * @param targetDepartmentParentIds
	 */
	public void updateFullId(String sourcesDepartmentFullId,String targetDepartmentFullId){
		mapper.updateFullId(sourcesDepartmentFullId, targetDepartmentFullId);
	}
	
}
